package web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import objects.Board;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

/**
 * Servlet implementation class TimerServlet
 */
@WebServlet(name = "Timer", urlPatterns =
{
    "/Timer"
})
public class TimerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TimerServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		// Getting the current player that requested operations from client.
		String plName = request.getParameter("browserPlayer");
		String actID = request.getParameter("whatAction");
		int nAct = Integer.parseInt(actID);
		PrintWriter out = response.getWriter();
		out.flush();
		Board boradInst = Board.getInstance();
		
		if (boradInst != null && boradInst.getBdGameData() != null)
		{
			JsonArray jsArr = new JsonArray();
			JsonObject jsPl = new JsonObject();
			jsPl.addProperty("plRequested", plName);
			jsPl.addProperty("currentPlayer", Board.getInstance().getCurrPlayerInstance().getPlayerName());
			jsArr.add(jsPl);
			if (boradInst.getJsActions(nAct) != null)
			{
				jsArr.addAll(boradInst.getJsActions(nAct));
			}
			
			
			String strDat = new Gson().toJson(jsArr);
			out.print(strDat);
		}	}

}
